extends Control

# 预加载自定义类
const MapNodeButton = preload("res://scripts/MapNodeButton.gd")
const AdvancedMapGenerator = preload("res://scripts/AdvancedMapGenerator.gd")
const MapNode = preload("res://scripts/MapNode.gd")
const MapConnection = preload("res://scripts/MapConnection.gd")

@onready var health_label = $TopPanel/PlayerInfo/HealthLabel
@onready var energy_label = $TopPanel/PlayerInfo/EnergyLabel
@onready var gold_label = $TopPanel/PlayerInfo/GoldLabel
@onready var floor_label = $TopPanel/PlayerInfo/FloorLabel
@onready var seed_label = $TopPanel/PlayerInfo/SeedLabel

@onready var map_container = $MapContainer
@onready var map_grid = $MapContainer/MapGrid
@onready var deck_button = $BottomPanel/ActionButtons/DeckButton
@onready var relics_button = $BottomPanel/ActionButtons/RelicsButton
@onready var potions_button = $BottomPanel/ActionButtons/PotionsButton
@onready var new_map_button = $BottomPanel/ActionButtons/NewMapButton
@onready var seed_button = $BottomPanel/ActionButtons/SeedButton

var game_data: GameData
var map_generator: AdvancedMapGenerator
var current_map: Array[Array] = []
var node_buttons: Array[Array] = []
var connections: Array[MapConnection] = []
var connection_layer: Control

func _ready():
	game_data = GameData.get_instance()
	
	# 确保游戏数据正确初始化
	print("游戏数据初始化 - 当前楼层: ", game_data.current_floor)
	if game_data.current_floor <= 0:
		game_data.current_floor = 1
		print("重置当前楼层为 1")
	
	# 设置背景美化
	_setup_background()
	
	# 连接按钮信号
	deck_button.pressed.connect(_on_deck_pressed)
	relics_button.pressed.connect(_on_relics_pressed)
	potions_button.pressed.connect(_on_potions_pressed)
	new_map_button.pressed.connect(_on_new_map_pressed)
	seed_button.pressed.connect(_on_seed_pressed)
	
	# 如果地图已存在，直接更新；否则生成新地图
	if current_map.size() > 0:
		_update_map_for_current_floor()
	else:
		_generate_new_map()
	
	_update_ui()
	
	# 检查是否从战斗场景返回
	_check_battle_return()
	
	# 添加测试点击事件
	await get_tree().process_frame
	_test_map_interaction()
	
	# 延迟修复 mouse_filter 问题
	await get_tree().process_frame
	await get_tree().process_frame
	_fix_mouse_filters()
	
	# 测试按钮交互
	await get_tree().process_frame
	_test_button_interaction()
	
	# 添加测试滚动按钮
	_add_debug_scroll_button()
	
	# 调试游戏开始状态
	_debug_game_start_state()

func _test_map_interaction():
	# 测试地图交互
	print("=== 地图交互测试 ===")
	print("MapContainer: ", map_container)
	print("MapContainer children: ", map_container.get_children())
	
	var content_container = map_container.get_node_or_null("ContentContainer")
	if content_container:
		print("ContentContainer found: ", content_container)
		print("ContentContainer children: ", content_container.get_children())
		
		var node_layer = content_container.get_node_or_null("NodeLayer")
		if node_layer:
			print("NodeLayer found: ", node_layer)
			print("NodeLayer children: ", node_layer.get_children())
			
			# 检查第一个节点按钮
			if node_layer.get_child_count() > 0:
				var first_button = node_layer.get_child(0)
				print("First button: ", first_button)
				print("First button class: ", first_button.get_class())
				print("First button mouse filter: ", first_button.mouse_filter)
				print("First button disabled: ", first_button.disabled)
		else:
			print("NodeLayer not found!")
	else:
		print("ContentContainer not found!")
	
	print("=== 测试完成 ===")

func _fix_mouse_filters():
	# 修复所有节点按钮的 mouse_filter
	print("=== 修复 Mouse Filter ===")
	var content_container = map_container.get_node_or_null("ContentContainer")
	if content_container:
		print("ContentContainer found")
		var node_layer = content_container.get_node_or_null("NodeLayer")
		if node_layer:
			print("NodeLayer found with ", node_layer.get_child_count(), " children")
			for i in range(node_layer.get_child_count()):
				var child = node_layer.get_child(i)
				print("Child ", i, ": ", child.get_class(), " - mouse_filter: ", child.mouse_filter, " - disabled: ", child.disabled)
				if child is Button:
					print("Before fix - mouse_filter: ", child.mouse_filter)
					child.mouse_filter = Control.MOUSE_FILTER_PASS
					print("After fix - mouse_filter: ", child.mouse_filter)
					print("Fixed mouse_filter for button: ", child)
		else:
			print("NodeLayer not found!")
	else:
		print("ContentContainer not found!")
	print("=== Mouse Filter 修复完成 ===")

func _test_button_interaction():
	# 测试按钮交互
	print("=== 测试按钮交互 ===")
	var content_container = map_container.get_node_or_null("ContentContainer")
	if content_container:
		var node_layer = content_container.get_node_or_null("NodeLayer")
		if node_layer and node_layer.get_child_count() > 0:
			var first_button = node_layer.get_child(0)
			print("测试第一个按钮:")
			print("  类型: ", first_button.get_class())
			print("  鼠标过滤: ", first_button.mouse_filter)
			print("  禁用状态: ", first_button.disabled)
			print("  可见性: ", first_button.visible)
			print("  透明度: ", first_button.modulate)
			print("  位置: ", first_button.position)
			print("  大小: ", first_button.size)
			print("  父节点: ", first_button.get_parent())
			print("  祖父节点: ", first_button.get_parent().get_parent())
	print("=== 按钮交互测试完成 ===")

func _check_battle_return():
	# 检查是否从战斗场景返回，如果是则更新地图状态
	print("检查战斗返回状态 - in_battle: ", game_data.in_battle, " current_floor: ", game_data.current_floor)
	
	if game_data.in_battle == false and current_map.size() > 0:
		print("从战斗返回，更新地图状态")
		
		# 标记所有当前节点为已访问，但保持 is_current 状态用于路径解锁
		var current_nodes_found = 0
		for floor_index in range(current_map.size()):
			var floor_nodes = current_map[floor_index]
			for node_index in range(floor_nodes.size()):
				var node = floor_nodes[node_index]
				if node.is_current:
					node.is_visited = true
					# 不立即清除 is_current 状态，让 _update_map_for_current_floor 能找到当前节点
					current_nodes_found += 1
					print("标记节点为已访问: ", node.get_node_name(), " 楼层: ", node.floor_number, " 楼层索引: ", floor_index)
		
		print("找到并标记了 ", current_nodes_found, " 个当前节点")
		
		# 如果没找到当前节点，可能战斗已经结束，手动标记第一层节点为已访问
		if current_nodes_found == 0:
			print("未找到当前节点，手动标记第一层节点为已访问")
			for node in current_map[0]:
				if not node.is_visited:
					node.is_visited = true
					print("手动标记节点为已访问: ", node.get_node_name())
		
		# 更新地图显示
		_update_map_for_current_floor()
		_update_ui()
	else:
		print("无需更新地图状态")

func _debug_all_nodes_status():
	# 调试所有节点状态
	print("=== 所有节点状态调试 ===")
	for floor_index in range(current_map.size()):
		var floor_nodes = current_map[floor_index]
		print("楼层 ", floor_index + 1, " (索引 ", floor_index, "):")
		for node_index in range(floor_nodes.size()):
			var node = floor_nodes[node_index]
			print("  节点 ", node_index, ": ", node.get_node_name(), 
				  " - visited: ", node.is_visited, 
				  " - accessible: ", node.is_accessible, 
				  " - current: ", node.is_current,
				  " - connections: ", node.next_floor_connections.size())
	print("=== 节点状态调试结束 ===")

func _setup_background():
	# 创建渐变背景
	var background = $Background
	var gradient = Gradient.new()
	gradient.add_point(0.0, Color(0.05, 0.1, 0.15, 1.0))
	gradient.add_point(0.5, Color(0.08, 0.15, 0.25, 1.0))
	gradient.add_point(1.0, Color(0.1, 0.2, 0.3, 1.0))
	
	# 创建背景纹理
	var gradient_texture = GradientTexture2D.new()
	gradient_texture.gradient = gradient
	gradient_texture.fill_from = Vector2(0, 0)
	gradient_texture.fill_to = Vector2(0, 1)
	
	# 应用背景样式
	var style_box = StyleBoxTexture.new()
	style_box.texture = gradient_texture
	background.add_theme_stylebox_override("panel", style_box)
	
	# 设置按钮样式
	_setup_button_styles()

func _setup_button_styles():
	# 为所有按钮设置现代化样式
	var buttons = [
		deck_button, relics_button, potions_button, 
		new_map_button, seed_button
	]
	
	for button in buttons:
		_setup_modern_button_style(button)

func _setup_modern_button_style(button: Button):
	# 正常状态样式
	var normal_style = StyleBoxFlat.new()
	normal_style.bg_color = Color(0.2, 0.3, 0.4, 0.8)
	normal_style.corner_radius_top_left = 8
	normal_style.corner_radius_top_right = 8
	normal_style.corner_radius_bottom_left = 8
	normal_style.corner_radius_bottom_right = 8
	normal_style.border_width_left = 1
	normal_style.border_width_right = 1
	normal_style.border_width_top = 1
	normal_style.border_width_bottom = 1
	normal_style.border_color = Color(0.4, 0.5, 0.6, 1.0)
	
	# 悬停状态样式
	var hover_style = StyleBoxFlat.new()
	hover_style.bg_color = Color(0.3, 0.4, 0.5, 0.9)
	hover_style.corner_radius_top_left = 8
	hover_style.corner_radius_top_right = 8
	hover_style.corner_radius_bottom_left = 8
	hover_style.corner_radius_bottom_right = 8
	hover_style.border_width_left = 1
	hover_style.border_width_right = 1
	hover_style.border_width_top = 1
	hover_style.border_width_bottom = 1
	hover_style.border_color = Color(0.5, 0.6, 0.7, 1.0)
	
	# 按下状态样式
	var pressed_style = StyleBoxFlat.new()
	pressed_style.bg_color = Color(0.1, 0.2, 0.3, 1.0)
	pressed_style.corner_radius_top_left = 8
	pressed_style.corner_radius_top_right = 8
	pressed_style.corner_radius_bottom_left = 8
	pressed_style.corner_radius_bottom_right = 8
	pressed_style.border_width_left = 1
	pressed_style.border_width_right = 1
	pressed_style.border_width_top = 1
	pressed_style.border_width_bottom = 1
	pressed_style.border_color = Color(0.3, 0.4, 0.5, 1.0)
	
	# 应用样式
	button.add_theme_stylebox_override("normal", normal_style)
	button.add_theme_stylebox_override("hover", hover_style)
	button.add_theme_stylebox_override("pressed", pressed_style)
	
	# 设置字体颜色
	button.add_theme_color_override("font_color", Color.WHITE)
	button.add_theme_color_override("font_hover_color", Color(0.9, 0.9, 1.0))
	button.add_theme_color_override("font_pressed_color", Color(0.8, 0.8, 1.0))

func _generate_new_map():
	# 生成随机种子
	var seed_value = randi()
	map_generator = AdvancedMapGenerator.new(seed_value)
	current_map = map_generator.generate_map()
	# 重置为第一层，确保首层可点击
	game_data.current_floor = 1
	
	# 显示种子
	seed_label.text = "种子: " + str(seed_value)
	
	# 先显式设置第1层可达，其他层不可达
	for floor_nodes in current_map:
		for node in floor_nodes:
			node.is_accessible = false
	if current_map.size() > 0:
		for node in current_map[0]:
			node.is_accessible = true
	
	# 创建UI并刷新按钮状态
	_create_map_ui()
	_force_update_button_states()
	await get_tree().process_frame
	_set_scroll_to_bottom()

func _create_map_ui():
	# 清除现有UI（但保留场景文件中的MapGrid作为基础结构）
	# 只清除我们动态创建的内容
	for child in map_container.get_children():
		if child.name in ["ConnectionLayer", "NodeLayer", "Legend"]:
			child.queue_free()
	
	# 清除现有的MapGrid内容
	var map_grid = map_container.get_node_or_null("MapGrid")
	if map_grid:
		for child in map_grid.get_children():
			child.queue_free()
	
	node_buttons.clear()
	connections.clear()
	
	# 创建连接层（底层）- 简化地图后不再需要连线层，但保留内容容器和尺寸计算
	_create_connection_layer()
	
	# 创建节点层（顶层）
	_create_node_layer()
	
	# 简化：不再创建连线
	# _create_connections()
	
	# 创建图标说明
	_create_legend()

func _create_node_layer():
	# 获取内容容器
	var content_container = map_container.get_node("ContentContainer")
	
	# 创建节点层，放在连接层之上
	var node_layer = Control.new()
	node_layer.name = "NodeLayer"
	node_layer.mouse_filter = Control.MOUSE_FILTER_PASS
	node_layer.anchors_preset = Control.PRESET_TOP_LEFT
	node_layer.anchor_top = 0.0
	node_layer.anchor_left = 0.0
	node_layer.anchor_right = 0.0
	node_layer.anchor_bottom = 0.0
	node_layer.size = content_container.custom_minimum_size
	
	# 将节点层添加到内容容器（在连接层之上）
	content_container.add_child(node_layer)
	# 确保节点层位于最顶层，避免被遮挡
	content_container.move_child(node_layer, content_container.get_child_count() - 1)
	
	# 创建地图节点按钮
	for floor_index in range(current_map.size()):
		var floor_nodes = current_map[floor_index]
		var floor_buttons: Array[Control] = []
		
		for node in floor_nodes:
			var node_button = MapNodeButton.new()
			node_button.setup_node(node)
			
			# 计算节点在地图上的实际位置
			var position = _calculate_node_position(node)
			node_button.position = position
				
				# 连接点击信号
			node_button.pressed.connect(func(): _on_node_clicked(node, node_button))
				
			print("Connected signal for node: ", node.get_node_name(), " at position: ", position)
			print("Node button mouse filter before: ", node_button.mouse_filter)
			print("Node button disabled: ", node_button.disabled)
			
			# 强制设置鼠标过滤，确保可以接收点击事件（在连接信号后设置）
			node_button.mouse_filter = Control.MOUSE_FILTER_PASS
			# 使用绝对定位
			node_button.anchors_preset = Control.PRESET_TOP_LEFT
			node_button.anchor_top = 0.0
			node_button.anchor_left = 0.0
			node_button.anchor_right = 0.0
			node_button.anchor_bottom = 0.0
			
			node_layer.add_child(node_button)
			
			# 再次强制设置鼠标过滤，确保在添加到容器后仍然有效
			node_button.mouse_filter = Control.MOUSE_FILTER_PASS
			
			floor_buttons.append(node_button)
		
		node_buttons.append(floor_buttons)
	
func _create_legend():
	# 创建地图图例，放在右上角
	var legend = Panel.new()
	legend.name = "MapLegend"
	legend.anchors_preset = Control.PRESET_TOP_RIGHT
	legend.anchor_top = 0.0
	legend.anchor_right = 1.0
	legend.anchor_bottom = 0.0
	legend.offset_left = -300
	legend.offset_top = 10
	legend.offset_right = -10
	legend.offset_bottom = 200
	
	# 设置图例样式
	var legend_style = StyleBoxFlat.new()
	legend_style.bg_color = Color(0.1, 0.15, 0.2, 0.9)
	legend_style.corner_radius_top_left = 10
	legend_style.corner_radius_top_right = 10
	legend_style.corner_radius_bottom_left = 10
	legend_style.corner_radius_bottom_right = 10
	legend_style.border_width_left = 2
	legend_style.border_width_right = 2
	legend_style.border_width_top = 2
	legend_style.border_width_bottom = 2
	legend_style.border_color = Color(0.3, 0.4, 0.5, 1.0)
	legend.add_theme_stylebox_override("panel", legend_style)
	
	# 创建图例容器
	var legend_container = VBoxContainer.new()
	legend_container.anchors_preset = Control.PRESET_FULL_RECT
	legend_container.offset_left = 10
	legend_container.offset_top = 10
	legend_container.offset_right = -10
	legend_container.offset_bottom = -10
	legend.add_child(legend_container)
	
	# 添加图例标题
	var title_label = Label.new()
	title_label.text = "地图说明"
	title_label.add_theme_font_size_override("font_size", 16)
	title_label.add_theme_color_override("font_color", Color.WHITE)
	title_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	legend_container.add_child(title_label)
	
	# 添加分隔线
	var separator = HSeparator.new()
	legend_container.add_child(separator)
	
	# 添加节点类型说明
	var node_types = [
		["⚔️", "战斗", "与考试怪物战斗"],
		["👑", "精英", "与强大的精英考试战斗"],
		["💀", "Boss", "与最终Boss战斗"],
		["🏠", "汉府", "休息恢复生命值和能量"],
		["🛒", "吾悦", "购买卡牌、遗物和药水"],
		["❓", "事件", "遇到随机事件"],
		["💎", "宝箱", "获得遗物或药水"]
	]
	
	for node_type in node_types:
		var item_container = HBoxContainer.new()
		legend_container.add_child(item_container)
		
		var icon_label = Label.new()
		icon_label.text = node_type[0]
		icon_label.add_theme_font_size_override("font_size", 18)
		icon_label.custom_minimum_size.x = 30
		item_container.add_child(icon_label)
		
		var text_container = VBoxContainer.new()
		item_container.add_child(text_container)
		
		var name_label = Label.new()
		name_label.text = node_type[1]
		name_label.add_theme_font_size_override("font_size", 12)
		name_label.add_theme_color_override("font_color", Color.WHITE)
		text_container.add_child(name_label)
		
		var desc_label = Label.new()
		desc_label.text = node_type[2]
		desc_label.add_theme_font_size_override("font_size", 10)
		desc_label.add_theme_color_override("font_color", Color(0.8, 0.8, 0.8))
		desc_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
		text_container.add_child(desc_label)
	
	# 添加分隔线
	var separator2 = HSeparator.new()
	legend_container.add_child(separator2)
	
	# 添加路径状态说明
	var path_status = [
		["●", "当前位置", "你当前所在的节点"],
		["✓", "已完成", "已经完成的事件"],
		["🔒", "未解锁", "还没有解锁的路径"],
		["黄色边框", "可选择", "可以点击进入的事件"]
	]
	
	var status_title = Label.new()
	status_title.text = "路径状态"
	status_title.add_theme_font_size_override("font_size", 14)
	status_title.add_theme_color_override("font_color", Color.WHITE)
	legend_container.add_child(status_title)
	
	for status in path_status:
		var status_container = HBoxContainer.new()
		legend_container.add_child(status_container)
		
		var status_icon = Label.new()
		status_icon.text = status[0]
		status_icon.add_theme_font_size_override("font_size", 14)
		status_icon.custom_minimum_size.x = 30
		status_container.add_child(status_icon)
		
		var status_text = Label.new()
		status_text.text = status[1] + ": " + status[2]
		status_text.add_theme_font_size_override("font_size", 10)
		status_text.add_theme_color_override("font_color", Color(0.8, 0.8, 0.8))
		status_container.add_child(status_text)
	
	# 将图例添加到地图容器
	map_container.add_child(legend)

func _calculate_node_position(node: MapNode) -> Vector2:
	# 交错菱形布局的节点位置计算
	var floor_spacing = 120.0
	var node_spacing = 180.0
	var start_x = 200.0
	
	var total_floors = current_map.size()
	var start_y = 50.0
	var end_padding = 100.0
	var map_height = start_y + (total_floors - 1) * floor_spacing + end_padding
	var first_floor_y = map_height - end_padding - 50.0
	
	# 偶数层向右错开半个节点间距，奇数层不偏移（或反之均可）
	var is_even_floor = (node.floor_number % 2) == 0
	var x_offset = (node_spacing * 0.5) if is_even_floor else 0.0
	
	var x = start_x + x_offset + node.x_position * node_spacing
	var y = first_floor_y - (node.floor_number - 1) * floor_spacing
	
	return Vector2(x, y)

func _create_connection_layer():
	# 获取或创建内容容器
	var content_container = map_container.get_node_or_null("ContentContainer")
	if not content_container:
		_setup_scroll_area()
		content_container = map_container.get_node("ContentContainer")
	
	# 创建连接层，放在底层
	connection_layer = Control.new()
	connection_layer.name = "ConnectionLayer"
	connection_layer.mouse_filter = Control.MOUSE_FILTER_IGNORE
	connection_layer.anchors_preset = Control.PRESET_TOP_LEFT
	connection_layer.anchor_top = 0.0
	connection_layer.anchor_left = 0.0
	connection_layer.anchor_right = 0.0
	connection_layer.anchor_bottom = 0.0
	connection_layer.size = content_container.custom_minimum_size
	
	# 将连接层添加到内容容器（作为第一个子节点，确保在底层）
	content_container.add_child(connection_layer)
	content_container.move_child(connection_layer, 0)

func _setup_scroll_area():
	# 设置地图滚动区域
	if map_container is ScrollContainer:
		# 计算地图内容大小（更精确的计算）
		var floor_count = current_map.size()
		var floor_spacing = 120  # 楼层间距
		var start_y = 50  # 起始位置
		var end_padding = 100  # 底部填充
		
		# 计算实际需要的高度：从第一层到底部的距离 + 填充
		var map_height = start_y + (floor_count - 1) * floor_spacing + end_padding
		var map_width = 800  # 地图宽度
		
		# 创建一个内容容器来设置滚动区域大小
		var content_container = Control.new()
		content_container.name = "ContentContainer"
		content_container.custom_minimum_size = Vector2(map_width, map_height)
		content_container.anchors_preset = Control.PRESET_TOP_LEFT
		content_container.anchor_top = 0.0
		content_container.anchor_left = 0.0
		content_container.anchor_right = 0.0
		content_container.anchor_bottom = 0.0
		
		# 将内容容器添加到滚动容器
		map_container.add_child(content_container)
		
		print("Map height calculated: ", map_height, " for ", floor_count, " floors")
		
		# 延迟设置滚动位置
		await get_tree().process_frame
		await get_tree().process_frame
		
		# 设置滚动到底部（显示第一层）
		_set_scroll_to_bottom()

func _set_scroll_to_bottom():
	# 确保地图滚动到底部，显示第一层
	print("=== 开始设置滚动到底部 ===")
	
	# 等待滚动条更新
	await get_tree().process_frame
	await get_tree().process_frame
	
	var scroll_bar = map_container.get_v_scroll_bar()
	var content_container = map_container.get_node_or_null("ContentContainer")
	
	if content_container:
		var content_height = content_container.custom_minimum_size.y
		var viewport_height = map_container.size.y
		
		print("Content height: ", content_height, " Viewport height: ", viewport_height)
		
		if content_height > viewport_height:
			# 计算需要滚动的距离（显示底部）
			var scroll_distance = content_height - viewport_height
			map_container.scroll_vertical = scroll_distance
			print("Set scroll to bottom: ", scroll_distance)
			
			# 再次检查滚动条状态
			if scroll_bar:
				print("ScrollBar max: ", scroll_bar.max_value, " current: ", scroll_bar.value)
		else:
			print("Content fits in viewport, no scrolling needed")
	else:
		print("No content container found!")
	
	# 调试信息
	_debug_map_display()

func _debug_map_display():
	# 调试地图显示状态
	var content_container = map_container.get_node_or_null("ContentContainer")
	if content_container:
		print("=== 地图显示调试 ===")
		print("ContentContainer size: ", content_container.custom_minimum_size)
		print("MapContainer size: ", map_container.size)
		print("MapContainer scroll: ", map_container.scroll_vertical)
		
		var scroll_bar = map_container.get_v_scroll_bar()
		if scroll_bar:
			print("ScrollBar max: ", scroll_bar.max_value, " current: ", scroll_bar.value)
		
		# 检查第一层节点的位置
		var node_layer = content_container.get_node_or_null("NodeLayer")
		if node_layer:
			print("NodeLayer children count: ", node_layer.get_child_count())
			for i in range(min(3, node_layer.get_child_count())):  # 只显示前3个（第一层）
				var button = node_layer.get_child(i)
				if button is MapNodeButton:
					print("Node ", i, " (", button.map_node.get_node_name(), ") position: ", button.position, " size: ", button.size)
		print("=== 调试结束 ===")

func _add_debug_scroll_button():
	# 添加调试滚动按钮
	var debug_button = Button.new()
	debug_button.text = "滚动到底部"
	debug_button.size = Vector2(120, 40)
	debug_button.position = Vector2(10, 10)
	debug_button.pressed.connect(_on_debug_scroll_pressed)
	
	# 添加战斗返回测试按钮
	var battle_return_button = Button.new()
	battle_return_button.text = "测试战斗返回"
	battle_return_button.size = Vector2(120, 40)
	battle_return_button.position = Vector2(140, 10)
	battle_return_button.pressed.connect(_on_debug_battle_return_pressed)
	
	# 添加第一层调试按钮
	var first_floor_button = Button.new()
	first_floor_button.text = "调试第一层"
	first_floor_button.size = Vector2(120, 40)
	first_floor_button.position = Vector2(270, 10)
	first_floor_button.pressed.connect(_on_debug_first_floor_pressed)
	
	# 添加到地图容器
	map_container.add_child(debug_button)
	map_container.add_child(battle_return_button)
	map_container.add_child(first_floor_button)
	print("添加了调试按钮")

func _on_debug_scroll_pressed():
	print("=== 手动滚动到底部 ===")
	_set_scroll_to_bottom()

func _on_debug_battle_return_pressed():
	print("=== 手动测试战斗返回 ===")
	# 模拟战斗结束状态
	game_data.in_battle = false
	game_data.current_floor = 2
	print("设置 in_battle = false, current_floor = 2")
	
	# 手动标记第一层节点为已访问
	for node in current_map[0]:
		node.is_visited = true
		node.is_current = false
		print("手动标记节点为已访问: ", node.get_node_name())
	
	# 调用战斗返回检查
	_check_battle_return()

func _on_debug_first_floor_pressed():
	print("=== 调试第一层节点 ===")
	# 强制设置第一层节点为可访问
	for node in current_map[0]:
		node.is_accessible = true
		node.is_visited = false
		node.is_current = false
		print("强制设置第一层节点可访问: ", node.get_node_name())
	
	# 重新创建地图UI
	_create_map_ui()
	_force_update_button_states()
	
	# 调试节点层级
	_debug_node_layers()

func _debug_node_layers():
	print("=== 节点层级调试 ===")
	var content_container = map_container.get_node_or_null("ContentContainer")
	if content_container:
		print("ContentContainer children:")
		for i in range(content_container.get_child_count()):
			var child = content_container.get_child(i)
			print("  Child ", i, ": ", child.name, " - ", child.get_class())
		
		var node_layer = content_container.get_node_or_null("NodeLayer")
		if node_layer:
			print("NodeLayer children (", node_layer.get_child_count(), "):")
			for i in range(min(5, node_layer.get_child_count())):  # 只显示前5个
				var button = node_layer.get_child(i)
				if button is MapNodeButton:
					print("  Button ", i, ": ", button.map_node.get_node_name(), 
						  " pos: ", button.position, 
						  " size: ", button.size,
						  " mouse_filter: ", button.mouse_filter,
						  " disabled: ", button.disabled,
						  " visible: ", button.visible)
	print("=== 层级调试结束 ===")

func _debug_game_start_state():
	print("=== 游戏开始状态调试 ===")
	print("GameData current_floor: ", game_data.current_floor)
	print("Current map size: ", current_map.size())
	
	if current_map.size() > 0:
		print("第一层节点状态:")
		for i in range(current_map[0].size()):
			var node = current_map[0][i]
			print("  节点 ", i, ": ", node.get_node_name(), 
				  " - accessible: ", node.is_accessible, 
				  " - visited: ", node.is_visited, 
				  " - current: ", node.is_current)
	else:
		print("地图为空！")
	print("=== 游戏开始状态调试结束 ===")

func _create_connections():
	# 清除现有连接
	if connection_layer:
		for child in connection_layer.get_children():
			child.queue_free()
	connections.clear()
	
	print("=== 创建连接 ===")
	# 使用预定义的连接关系创建连线
	for floor_index in range(current_map.size() - 1):
		var current_floor_nodes = current_map[floor_index]
		print("楼层 ", floor_index + 1, " 有 ", current_floor_nodes.size(), " 个节点")
		
		for current_node in current_floor_nodes:
			print("节点 ", current_node.get_node_name(), " 连接到 ", current_node.next_floor_connections.size(), " 个下一层节点")
			# 使用节点预定义的连接关系
			for next_node in current_node.next_floor_connections:
				print("  连接到: ", next_node.get_node_name())
				var connection = MapConnection.new(current_node, next_node)
				# 传递地图信息给连接对象
				connection.set_map_info(current_map.size())
				connections.append(connection)
				connection_layer.add_child(connection)
	
	print("总共创建了 ", connections.size(), " 个连接")

func _on_node_clicked(node: MapNode, button: Control):
	print("=== 节点点击事件触发 ===")
	print("Node clicked: ", node.get_node_name())
	print("Node accessible: ", node.is_accessible)
	print("Node visited: ", node.is_visited)
	print("Node current: ", node.is_current)
	print("Button disabled: ", button.disabled)
	print("Button mouse_filter: ", button.mouse_filter)
	print("=== 节点点击事件结束 ===")
	
	# 极简模式：无条件进入节点，便于先打通点击与战斗流程
	print("Entering node (simple mode): ", node.get_node_name())
	_enter_selectable_node(node)

func _enter_selectable_node(node: MapNode):
	# 清除所有节点的当前状态
	for floor_nodes in current_map:
		for n in floor_nodes:
			n.is_current = false
	
	# 设置当前节点
	node.is_current = true
	
	# 进入节点
	node.enter_node()

	# 简化推进：选择即前进到下一层（在触发事件前执行，避免切场景后未更新）
	if game_data.current_floor < current_map.size():
		game_data.current_floor += 1
	
	# 处理不同类型的节点
	match node.node_type:
		MapNode.NodeType.COMBAT:
			_start_combat(false)
		MapNode.NodeType.ELITE:
			_start_combat(true)
		MapNode.NodeType.BOSS:
			_start_boss_combat()
		MapNode.NodeType.REST:
			_show_rest_event()
		MapNode.NodeType.SHOP:
			_show_shop_event()
		MapNode.NodeType.EVENT:
			_show_random_event()
		MapNode.NodeType.TREASURE:
			_show_treasure_event()
		MapNode.NodeType.REMOVE_CARD:
			_show_remove_card_event()
		MapNode.NodeType.UPGRADE_CARD:
			_show_upgrade_card_event()
		MapNode.NodeType.HEAL_EVENT:
			_show_heal_event()
		MapNode.NodeType.RANDOM_CARD:
			_show_random_card_event()
	
	# 更新地图显示
	_create_map_ui()

func _show_node_completed_info(node: MapNode):
	var dialog = AcceptDialog.new()
	dialog.title = "已完成的事件"
	dialog.dialog_text = "这个事件已经完成了！\n" + node.get_node_name() + "\n" + node.get_node_description()
	dialog.add_button("确定", true)
	add_child(dialog)
	dialog.popup_centered()
	dialog.confirmed.connect(func(): dialog.queue_free())

func _show_node_locked_info(node: MapNode):
	var dialog = AcceptDialog.new()
	dialog.title = "路径未解锁"
	dialog.dialog_text = "这个路径还没有解锁！\n" + node.get_node_name() + "\n" + node.get_node_description() + "\n\n请先完成前面的路径来解锁这个事件。"
	dialog.add_button("确定", true)
	add_child(dialog)
	dialog.popup_centered()
	dialog.confirmed.connect(func(): dialog.queue_free())

func _show_current_node_info(node: MapNode):
	var dialog = AcceptDialog.new()
	dialog.title = "当前位置"
	dialog.dialog_text = "你当前在这里！\n" + node.get_node_name() + "\n" + node.get_node_description() + "\n\n点击其他可访问的节点来继续前进。"
	dialog.add_button("确定", true)
	add_child(dialog)
	dialog.popup_centered()
	dialog.confirmed.connect(func(): dialog.queue_free())

func _start_combat(is_elite: bool):
	game_data.in_battle = true
	game_data.current_enemies.clear()
	
	if is_elite:
		_create_elite_enemies()
	else:
		_create_normal_enemies()
	
	get_tree().change_scene_to_file("res://scenes/BattleScene.tscn")

func _start_boss_combat():
	game_data.in_battle = true
	game_data.current_enemies.clear()
	_create_boss_enemies()
	get_tree().change_scene_to_file("res://scenes/BattleScene.tscn")

func _create_normal_enemies():
	var enemy_names = ["数学题", "语文题", "英语题", "物理题", "化学题"]
	var exam_types = ["数学考试", "语文考试", "英语考试", "物理考试", "化学考试"]
	
	var enemy_count = 1
	if game_data.current_floor > 5:
		enemy_count = 2
	if game_data.current_floor > 10:
		enemy_count = 3
	
	for i in range(enemy_count):
		var name = enemy_names[randi() % enemy_names.size()]
		var exam = exam_types[randi() % exam_types.size()]
		var health = 20 + game_data.current_floor * 3
		var damage = 5 + game_data.current_floor
		
		var enemy = Enemy.new(name, health, damage, exam, game_data.current_floor)
		game_data.current_enemies.append(enemy)

func _create_elite_enemies():
	var elite_names = ["期末考试", "模拟考试", "升学考试", "资格证考试"]
	var elite_exams = ["期末考试", "模拟考试", "升学考试", "资格证考试"]
	
	var name = elite_names[randi() % elite_names.size()]
	var exam = elite_exams[randi() % elite_exams.size()]
	var health = 60 + game_data.current_floor * 8
	var damage = 12 + game_data.current_floor * 2
	
	var enemy = Enemy.new(name, health, damage, exam, game_data.current_floor)
	enemy.is_elite = true
	game_data.current_enemies.append(enemy)

func _create_boss_enemies():
	var boss_names = ["高考", "研究生考试", "公务员考试", "司法考试"]
	var boss_exams = ["高考", "研究生考试", "公务员考试", "司法考试"]
	
	var name = boss_names[randi() % boss_names.size()]
	var exam = boss_exams[randi() % boss_exams.size()]
	var health = 150 + game_data.current_floor * 15
	var damage = 20 + game_data.current_floor * 3
	
	var enemy = Enemy.new(name, health, damage, exam, game_data.current_floor)
	enemy.is_boss = true
	game_data.current_enemies.append(enemy)

func _show_rest_event():
	var dialog = AcceptDialog.new()
	dialog.title = "汉府"
	dialog.dialog_text = "你在汉府好好休息了一番，恢复了所有生命值和能量。"
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	# 恢复生命值和能量
	game_data.player_health = game_data.player_max_health
	game_data.player_energy = game_data.player_max_energy
	
	dialog.confirmed.connect(func(): 
		dialog.queue_free()
		_update_ui()
	)

func _show_shop_event():
	var dialog = AcceptDialog.new()
	dialog.title = "吾悦广场"
	dialog.dialog_text = "欢迎来到吾悦广场！这里可以购买卡牌、遗物和药水。\n(商店功能待实现)"
	dialog.add_button("离开", true)
	add_child(dialog)
	dialog.popup_centered()
	
	dialog.confirmed.connect(func(): dialog.queue_free())

func _show_random_event():
	var events = [
		"你遇到了一个神秘的老师，他给了你一些建议。",
		"你发现了一本古老的教科书，从中学习到了新知识。",
		"你帮助了一个迷路的学生，获得了感谢。",
		"你参加了一个学习小组，获得了新的卡牌。"
	]
	
	var event_text = events[randi() % events.size()]
	var dialog = AcceptDialog.new()
	dialog.title = "随机事件"
	dialog.dialog_text = event_text
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	dialog.confirmed.connect(func(): dialog.queue_free())

func _show_treasure_event():
	var rewards = ["获得遗物", "获得药水", "获得金币", "获得卡牌"]
	var reward = rewards[randi() % rewards.size()]
	
	var dialog = AcceptDialog.new()
	dialog.title = "宝箱"
	dialog.dialog_text = "你发现了一个宝箱！" + reward
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	# 给予奖励
	match reward:
		"获得遗物":
			# 随机给予一个遗物
			pass
		"获得药水":
			# 随机给予一个药水
			pass
		"获得金币":
			game_data.player_gold += 50
		"获得卡牌":
			# 随机给予一张卡牌
			pass
	
	dialog.confirmed.connect(func(): 
		dialog.queue_free()
		_update_ui()
	)

func _show_remove_card_event():
	var dialog = AcceptDialog.new()
	dialog.title = "删牌事件"
	dialog.dialog_text = "你遇到了一个神秘的老师，他可以帮助你删除一张不需要的卡牌。"
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	# 这里可以添加删牌的具体逻辑
	dialog.confirmed.connect(func(): 
		dialog.queue_free()
		_update_ui()
	)

func _show_upgrade_card_event():
	var dialog = AcceptDialog.new()
	dialog.title = "升级卡牌"
	dialog.dialog_text = "你发现了一本古老的教科书，可以升级一张卡牌。"
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	# 这里可以添加升级卡牌的具体逻辑
	dialog.confirmed.connect(func(): 
		dialog.queue_free()
		_update_ui()
	)

func _show_heal_event():
	var dialog = AcceptDialog.new()
	dialog.title = "治疗事件"
	dialog.dialog_text = "你遇到了一个善良的医生，他为你治疗了伤势。"
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	# 恢复生命值
	game_data.player_health = min(game_data.player_health + 20, game_data.player_max_health)
	
	dialog.confirmed.connect(func(): 
		dialog.queue_free()
		_update_ui()
	)

func _show_random_card_event():
	var dialog = AcceptDialog.new()
	dialog.title = "随机卡牌"
	dialog.dialog_text = "你发现了一个神秘的宝箱，里面有一张随机卡牌。"
	dialog.add_button("继续", true)
	add_child(dialog)
	dialog.popup_centered()
	
	# 这里可以添加获得随机卡牌的具体逻辑
	dialog.confirmed.connect(func(): 
		dialog.queue_free()
		_update_ui()
	)

func _update_ui():
	# 更新玩家信息显示，添加图标和颜色
	health_label.text = "❤️ 生命值: " + str(game_data.player_health) + "/" + str(game_data.player_max_health)
	health_label.add_theme_color_override("font_color", Color(1.0, 0.3, 0.3))
	
	energy_label.text = "⚡ 能量: " + str(game_data.player_energy) + "/" + str(game_data.player_max_energy)
	energy_label.add_theme_color_override("font_color", Color(1.0, 1.0, 0.3))
	
	gold_label.text = "💰 金币: " + str(game_data.player_gold)
	gold_label.add_theme_color_override("font_color", Color(1.0, 0.8, 0.0))
	
	floor_label.text = "🏢 第 " + str(game_data.current_floor) + " 层"
	floor_label.add_theme_color_override("font_color", Color(0.7, 0.9, 1.0))
	
	# 设置字体样式
	var font_size = 16
	health_label.add_theme_font_size_override("font_size", font_size)
	energy_label.add_theme_font_size_override("font_size", font_size)
	gold_label.add_theme_font_size_override("font_size", font_size)
	floor_label.add_theme_font_size_override("font_size", font_size)
	
	# 更新地图显示当前楼层
	_update_map_for_current_floor()

func _update_map_for_current_floor():
	# 更新地图显示，高亮当前楼层的可访问节点
	print("更新地图状态 - 当前楼层: ", game_data.current_floor, " 地图楼层数: ", current_map.size())
	
	if current_map.size() > 0 and game_data.current_floor <= current_map.size():
		# 清除所有节点的状态
		for floor_nodes in current_map:
			for node in floor_nodes:
				node.is_accessible = false
				node.is_current = false
		
		# 简化：仅解锁当前楼层的所有节点
		var current_index = game_data.current_floor - 1
		if current_index >= 0 and current_index < current_map.size():
			for node in current_map[current_index]:
				node.is_accessible = true
				print("解锁当前层节点: ", node.get_node_name())
		
		# 重新创建地图UI以更新状态
		_create_map_ui()
		
		# 强制更新所有按钮状态
		_force_update_button_states()
		
		# 清除所有 is_current 状态（保持简化逻辑）
		for floor_nodes in current_map:
			for node in floor_nodes:
				node.is_current = false
		
		# 确保滚动到底部显示第一层
		await get_tree().process_frame
		_set_scroll_to_bottom()
		
		# 调试所有节点状态
		_debug_all_nodes_status()

func _force_update_button_states():
	# 强制更新所有按钮的状态
	print("=== 强制更新按钮状态 ===")
	var content_container = map_container.get_node_or_null("ContentContainer")
	if content_container:
		var node_layer = content_container.get_node_or_null("NodeLayer")
		if node_layer:
			for i in range(node_layer.get_child_count()):
				var button = node_layer.get_child(i)
				if button is MapNodeButton:
					# 强制设置 mouse_filter
					button.mouse_filter = Control.MOUSE_FILTER_PASS
					button._update_node_state()
					print("更新按钮状态: ", button.map_node.get_node_name(), " - accessible: ", button.map_node.is_accessible, " - disabled: ", button.disabled, " - mouse_filter: ", button.mouse_filter)
	print("=== 按钮状态更新完成 ===")

func _on_deck_pressed():
	_show_deck_viewer()

func _show_deck_viewer():
	# 创建卡牌查看器窗口
	var deck_window = Window.new()
	deck_window.title = "我的卡组 (" + str(game_data.deck.size()) + "张)"
	deck_window.size = Vector2i(800, 600)
	deck_window.position = Vector2i(100, 100)
	deck_window.borderless = false
	deck_window.always_on_top = true
	deck_window.popup_window = true
	
	# 创建主容器
	var main_container = VBoxContainer.new()
	deck_window.add_child(main_container)
	
	# 添加标题和统计信息
	var title_label = Label.new()
	title_label.text = "卡组总数: " + str(game_data.deck.size()) + " | 手牌: " + str(game_data.hand.size()) + " | 弃牌堆: " + str(game_data.discard_pile.size())
	title_label.add_theme_font_size_override("font_size", 16)
	title_label.add_theme_color_override("font_color", Color.WHITE)
	main_container.add_child(title_label)
	
	# 创建滚动容器
	var scroll_container = ScrollContainer.new()
	scroll_container.custom_minimum_size = Vector2(780, 500)
	main_container.add_child(scroll_container)
	
	# 创建网格容器
	var grid_container = GridContainer.new()
	grid_container.columns = 3
	grid_container.add_theme_constant_override("h_separation", 10)
	grid_container.add_theme_constant_override("v_separation", 10)
	scroll_container.add_child(grid_container)
	
	# 添加所有卡牌
	for card in game_data.deck:
		var card_container = _create_card_display(card)
		grid_container.add_child(card_container)
	
	# 添加关闭按钮
	var close_button = Button.new()
	close_button.text = "关闭"
	close_button.custom_minimum_size = Vector2(100, 40)
	close_button.pressed.connect(func(): deck_window.queue_free())
	main_container.add_child(close_button)
	
	# 显示窗口
	add_child(deck_window)
	deck_window.popup_centered_ratio(0.8)

func _create_card_display(card: Card) -> Control:
	# 创建卡牌显示容器
	var card_container = Panel.new()
	card_container.custom_minimum_size = Vector2(200, 280)
	
	# 设置卡牌背景样式
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.2, 0.3, 0.5, 0.9)
	style_box.border_width_left = 2
	style_box.border_width_right = 2
	style_box.border_width_top = 2
	style_box.border_width_bottom = 2
	style_box.border_color = Color(0.8, 0.8, 1.0)
	style_box.corner_radius_top_left = 8
	style_box.corner_radius_top_right = 8
	style_box.corner_radius_bottom_left = 8
	style_box.corner_radius_bottom_right = 8
	card_container.add_theme_stylebox_override("panel", style_box)
	
	# 创建垂直布局
	var vbox = VBoxContainer.new()
	vbox.add_theme_constant_override("separation", 5)
	card_container.add_child(vbox)
	
	# 卡牌名称
	var name_label = Label.new()
	name_label.text = card.name
	name_label.add_theme_font_size_override("font_size", 14)
	name_label.add_theme_color_override("font_color", Color.YELLOW)
	name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	name_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	vbox.add_child(name_label)
	
	# 卡牌类型
	var type_label = Label.new()
	type_label.text = "[" + card.get_card_type_name() + "]"
	type_label.add_theme_font_size_override("font_size", 10)
	type_label.add_theme_color_override("font_color", Color(0.8, 0.8, 0.8))
	type_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	vbox.add_child(type_label)
	
	# 卡牌消耗
	var cost_label = Label.new()
	cost_label.text = "消耗: " + str(card.cost) + " 能量"
	cost_label.add_theme_font_size_override("font_size", 11)
	cost_label.add_theme_color_override("font_color", Color(0.3, 0.8, 1.0))
	cost_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	vbox.add_child(cost_label)
	
	# 卡牌描述
	var desc_label = Label.new()
	desc_label.text = card.description
	desc_label.add_theme_font_size_override("font_size", 10)
	desc_label.add_theme_color_override("font_color", Color.WHITE)
	desc_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	desc_label.custom_minimum_size.y = 120
	vbox.add_child(desc_label)
	
	# 如果是攻击卡，显示伤害
	if card is AttackCard:
		var attack_card = card as AttackCard
		var damage_label = Label.new()
		damage_label.text = "伤害: " + str(attack_card.damage)
		damage_label.add_theme_font_size_override("font_size", 12)
		damage_label.add_theme_color_override("font_color", Color.RED)
		damage_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		vbox.add_child(damage_label)
	
	# 添加鼠标进入和离开效果
	card_container.mouse_entered.connect(func(): _on_card_mouse_entered(card_container))
	card_container.mouse_exited.connect(func(): _on_card_mouse_exited(card_container))
	card_container.gui_input.connect(func(event): _on_card_gui_input(card_container, card, event))
	
	return card_container

func _on_card_mouse_entered(card_container: Control):
	# 鼠标进入时的效果
	var style_box = card_container.get_theme_stylebox("panel") as StyleBoxFlat
	if style_box:
		style_box.border_color = Color.YELLOW
		style_box.bg_color = Color(0.3, 0.4, 0.6, 0.9)

func _on_card_mouse_exited(card_container: Control):
	# 鼠标离开时的效果
	var style_box = card_container.get_theme_stylebox("panel") as StyleBoxFlat
	if style_box:
		style_box.border_color = Color(0.8, 0.8, 1.0)
		style_box.bg_color = Color(0.2, 0.3, 0.5, 0.9)

func _on_card_gui_input(card_container: Control, card: Card, event: InputEvent):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
			_show_card_detail(card)

func _show_card_detail(card: Card):
	# 显示卡牌详细信息
	var detail_dialog = AcceptDialog.new()
	detail_dialog.title = card.name + " - 详细信息"
	
	var detail_text = "名称: " + card.name + "\n"
	detail_text += "类型: " + card.get_card_type_name() + "\n"
	detail_text += "消耗: " + str(card.cost) + " 能量\n"
	detail_text += "描述: " + card.description + "\n"
	
	if card is AttackCard:
		var attack_card = card as AttackCard
		detail_text += "伤害: " + str(attack_card.damage) + "\n"
	
	detail_dialog.dialog_text = detail_text
	detail_dialog.add_button("确定", true)
	add_child(detail_dialog)
	detail_dialog.popup_centered()
	detail_dialog.confirmed.connect(func(): detail_dialog.queue_free())

func _on_relics_pressed():
	var dialog = AcceptDialog.new()
	dialog.title = "我的遗物"
	var relics_info = "遗物数量: " + str(game_data.relics.size()) + "\n"
	if game_data.relics.size() == 0:
		relics_info += "暂无遗物"
	else:
		for relic in game_data.relics:
			relics_info += "• " + relic.name + ": " + relic.description + "\n"
	dialog.dialog_text = relics_info
	dialog.add_button("关闭", true)
	add_child(dialog)
	dialog.popup_centered()
	dialog.confirmed.connect(func(): dialog.queue_free())

func _on_potions_pressed():
	var dialog = AcceptDialog.new()
	dialog.title = "我的药水"
	var potions_info = "药水数量: " + str(game_data.potions.size()) + "\n"
	if game_data.potions.size() == 0:
		potions_info += "暂无药水"
	else:
		for potion in game_data.potions:
			potions_info += "• " + potion.name + ": " + potion.description + "\n"
	dialog.dialog_text = potions_info
	dialog.add_button("关闭", true)
	add_child(dialog)
	dialog.popup_centered()
	dialog.confirmed.connect(func(): dialog.queue_free())

func _on_new_map_pressed():
	_generate_new_map()
	_update_ui()

func _on_seed_pressed():
	var seed_dialog = preload("res://scenes/SeedDialog.tscn").instantiate()
	add_child(seed_dialog)
	seed_dialog.show_dialog(_on_seed_selected)

func _on_seed_selected(seed_value: int):
	_generate_map_with_seed(seed_value)
	_update_ui()

func _generate_map_with_seed(seed_value: int):
	map_generator = AdvancedMapGenerator.new(seed_value)
	current_map = map_generator.generate_map()
	# 重置为第一层，确保首层可点击
	game_data.current_floor = 1
	
	# 显示种子
	seed_label.text = "种子: " + str(seed_value)
	
	# 先显式设置第1层可达，其他层不可达
	for floor_nodes in current_map:
		for node in floor_nodes:
			node.is_accessible = false
	if current_map.size() > 0:
		for node in current_map[0]:
			node.is_accessible = true
	
	# 创建UI并刷新按钮状态
	_create_map_ui()
	_force_update_button_states()
	await get_tree().process_frame
	_set_scroll_to_bottom()
